class NoteType < ActiveRecord::Base
  belongs_to :ticket_template
  has_many :notes, :dependent => :destroy
  has_and_belongs_to_many :report_templates
  validates_presence_of :name
  validates_presence_of :vtype
  validates_length_of :name, :within => 1..255
  validates_presence_of :priority
  validates_numericality_of :priority
  validates_length_of :default_value, :maximum => 255, :if => Proc.new{|u| (u.vtype == "vstring") && (u.default_value)}
  validates_presence_of :select_text, :if => Proc.new{|u| (u.vtype == "vselect")}
  after_create :add_note_to_tickets
  
  attr_accessor :should_destroy
  
  serialize :choises

  
  def should_destroy?
    should_destroy.to_i == 1
  end
  
  def select_text
     self.choises ? self.choises * ";" : ""
  end
  
  def select_text=(st)
    self.choises = st.split(';')
  end
  
  def self.types
    [
	    ["String", "vstring"],
	    ["Text", "vtext"],
	    ["Checkbox","vcheckbox"],
	    ["Date", "vdate"],
	    ["Select", "vselect"]
	  ]
  end
  
  def default_v
    case self.vtype
      when "vstring", "vselect", "vtext"
        return self.default_value
      when "vcheckbox"
        return self.default_value && (self.default_value.length > 0)
      when "vdate"
        if self.default_value == 'today' 
          return Date.today
        else
          return (self.default_value && (self.default_value.length > 0)) ? self.default_value : ""
        end
    end
  end
 
  private
   
  def validate
    if (self.vtype == 'vdate') && (self.default_value) && (self.default_value != "") && (self.default_value != "today")
      self.default_value.to_date rescue errors.add(:default_value, "Date is not valid")
    elsif (self.vtype == "vselect") && (self.default_value) && (self.default_value.length > 0) && !(self.choises.include? self.default_value)
      errors.add(:default_value, "Select is not valid") 
    end
  end
  
  def add_note_to_tickets
    self.ticket_template.tickets.each { |ticket|
      note = Note.new(:ticket => ticket, :note_type => self)
      note.value = self.default_value
      note.save!
    }
  end

end
